import { _decorator, Component, Node, Vec3 } from 'cc';
import { Utils } from '../Data/Utils';
import { BattleManager } from './BattleManager';
import { MonsterView } from './MonsterView';
const { ccclass, property } = _decorator;

/**   单个怪物对自己的控制程序   */

@ccclass('Monster')
export class Monster{
    //怪物的视图类.
    private _view:MonsterView = null;
    private _speed = 8;

    //初始化视图类对象.
    public init(view:MonsterView){
        this._view = view;
        this._view.init(this);
        this._moveToRoadCenter();
    }

    //出生后，向马路中间集合.
    private _moveToRoadCenter(){
        //先计算一个马路中间的随机坐标，只修改x坐标，即垂直于马路的方向移动.
        const randomX = Utils.getRandomNumber(-5,5);
        const myPos = this.getWorldPosition();
        //计算出怪物要移动到的目标点.
        const targetPos = new Vec3(randomX,myPos.y,myPos.z);
        const dis = Math.abs(randomX - myPos.x);
        const time = dis/this._speed;
        //让怪物在指定的时间里移动到目标点.
        this._view.moveToTarget(targetPos,time,this.readyToAttack.bind(this));
    }

    //怪物移动到道路的中间后，可以开始准备进攻.
    public readyToAttack() {
        if (BattleManager.instance().isGameStart) {
            //向玩家角色冲过来.
            const myPos = this.getWorldPosition();
            //先计算一个马路中间的随机x坐标.
            const randomX = Utils.getRandomNumber(-4, 4);
            //计算出怪物要移动到的目标点,即玩家角色的坐标.
            const targetPos = new Vec3(randomX, myPos.y, -4);
            const dis = Vec3.distance(myPos, targetPos);
            let time = dis / this._speed;
            if(time<9){
                time = 9;
            }
            //让怪物在指定的时间里移动到目标点.
            this._view.moveToTarget(targetPos, time, this._playerDead.bind(this));
        }
    }

    //当怪物到达玩家角色附近，则游戏失败.
    private _playerDead(){
        console.warn('游戏失败');
        BattleManager.instance().playerDead();
    }

    //得到怪物当前的世界坐标.
    public getWorldPosition(){
        return this._view.node.worldPosition;
    }

    public stopMove(){
        this._view.stopMove();
    }

    //删除该怪物.
    public dispose(){
        this._view.dispose();
    }

    public onHurt(){
        BattleManager.instance().monsterDead(this);
    }
}
